package org.atlantis.grosbeak.cable;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.atlantis.grosbeak.logger.Logger;
import org.atlantis.grosbeak.logger.LoggerFactory;

/**
 * 分发过滤器，所有的请求都会通过此过滤器进行分发处理。所以必须配置此过滤器 到web.xml中。<br>
 * 同时在部署CableDispatcherFilter分发过滤器，可以设置一个encoding参数，这个 参数用来设置
 * <code>HttpServletRequest</code>和<code>HttpServletResponse</code>
 * 的编码。当然，完全可以不设置这个参数，因为默认就是“UTF-8”编码。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 */
public class CableDispatcherFilter implements Filter {

	private static Logger logger = LoggerFactory
			.getLogger(CableDispatcherFilter.class);

	private String encoding;
	private Postman postman;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(final FilterConfig config) throws ServletException {
		logger.debugFmt("Initialize the Cable Dispatcher ...");
		encoding = config.getInitParameter("encoding");
		if (encoding == null)
			encoding = "UTF-8";

		postman = new Postman();
		postman.setUp(new Provider() {
			public String getInitParameter(String key) {
				return config.getInitParameter(key);
			}

			public ServletContext getServletContext() {
				return config.getServletContext();
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) request;
		HttpServletResponse hreps = (HttpServletResponse) response;

		hreq.setCharacterEncoding(encoding);
		hreps.setCharacterEncoding(encoding);

		String method = hreq.getMethod();
		if ("GET".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method)) {
			if (!postman.service(hreq, hreps)) {
				chain.doFilter(request, response);
			}
			return;
		}
		hreps.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// 应该什么都不需要做吧！
	}
}
